/*
 * Created on 09.09.2006 by leck
 *
 */
package de.devisnik.eidle.picture;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

public class FileProvider implements IFileProvider {

    private List/*<File>*/ itsPathList = new ArrayList/*<File>*/();
    private int itsCurrentPosition;
    private final FilenameFilter itsFilenameFilter;

    public FileProvider(FilenameFilter filenameFilter) {
        itsFilenameFilter = filenameFilter;
    }

    /* (non-Javadoc)
     * @see de.devisnik.screensaver.screen.IFileProvider#addFile(java.io.File)
     */
    private void addFile(File file) throws FileNotFoundException {
        if (file.exists() && !file.isDirectory()) {
            if (itsFilenameFilter.accept(file, file.getName())) {
                itsPathList.add(file);
            }
        }
        else {
            throw new FileNotFoundException(file.getAbsolutePath());
        }
    }

    /* (non-Javadoc)
     * @see de.devisnik.screensaver.screen.IFileProvider#getSize()
     */
    public int getSize() {
        return itsPathList.size();
    }

    /* (non-Javadoc)
     * @see de.devisnik.screensaver.screen.IFileProvider#getNext()
     */
    public File getNext() {
        if (itsPathList.size() == 0 || itsCurrentPosition >= getSize()) {
            return null;
        }
        File nextFile = (File) itsPathList.get(itsCurrentPosition);
        itsCurrentPosition++;
        return nextFile;
    }

    /* (non-Javadoc)
     * @see de.devisnik.screensaver.screen.IFileProvider#reset()
     */
    public void reset() {
        itsCurrentPosition = 0;
    }

    /* (non-Javadoc)
     * @see de.devisnik.screensaver.screen.IFileProvider#addDirectory(java.io.File)
     */
    private void addDirectory(File directory) throws FileNotFoundException {
        if (!directory.exists() || !directory.isDirectory()) {
            throw new FileNotFoundException(directory.getAbsolutePath());
        }
        File[] files = directory.listFiles(itsFilenameFilter);
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            addFile(file);
            
        }
    }

    public boolean hasNext() {
        return itsCurrentPosition < getSize();
    }

    public void addResource(File file) throws FileNotFoundException {
        if (file.isDirectory()) {
            addDirectory(file);
        }
        else {
            addFile(file);
        }
    }

}
